<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" :model="findResult" class="demo-form-inline">
        <el-form-item >
          <el-input v-model="findResult.pname" placeholder="产品名"></el-input>
        </el-form-item>
        <el-form-item >
          价格区间：
        </el-form-item>
        <el-form-item >
          <el-input v-model="findResult.priceMin" placeholder="价格下限"></el-input>
        </el-form-item>
        <el-form-item >
          ~
        </el-form-item>
        <el-form-item >
          <el-input v-model="findResult.priceMax" placeholder="价格上限"></el-input>
        </el-form-item>
        <el-form-item >
          <el-select v-model="findResult.tid" placeholder="类别">
            <el-option label="所有类别" value="0"></el-option>
            <el-option :label="t.tname" :value="t.tid" v-for="t in typeList" :key="t.tid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addProduct()">添加商品</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="ProductList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>>
        <el-table-column
            label="商品编号"
            align="center"
            prop="pid">
        </el-table-column>
        <el-table-column
            label="商品名"
            align="center"
            prop="pname">
        </el-table-column>
        <el-table-column
            label="价格"
            align="center"
            prop="price">
        </el-table-column>
        <el-table-column
            label="类别"
            align="center"
            prop="tname">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 导航 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <el-dialog :title="title" :visible.sync="dialogFormVisible"  >
      ${{product}}
      <el-form :model="product" :rules="rules" ref="ruleForm">
        <el-form-item label="商品名" prop = "pname" :label-width="formLabelWidth">
          <el-input v-model="product.pname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop = "price" :label-width="formLabelWidth">
          <el-input v-model="product.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="tid" :label-width="formLabelWidth">
          <el-select v-model="product.tid" placeholder="请选择类别">
            <el-option :label="t.tname" :value="t.tid" v-for="t in typeList" :key="t.tid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import productApi from "@/api/product";
import typeApi from "@/api/type"

export default {
  data() {
    return {
      ProductList: [], // 存储学生数据
      page: 1, // 当前页 默认1
      pageSize: 10, // 默认每页显示10条
      total: 0, // 总记录数 默认0
      findResult: {}, //查询条件对象，初始化为空对象
      typeList: [],// 存储班级列表
      dialogFormVisible:false,
      formLabelWidth:'100px',
      product:{},
      multipleSelection:[],
      title:"添加商品",
      rules: {
        pname: [
          { required: true, message: '请输入商品名', trigger: 'blur' },
          { min: 2, max: 20, message: '商品名长度在2到20个字符之间', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请选择价格', trigger: 'change' }
        ],
        tname: [
          { required: true, message: '请选择类别', trigger: 'change' }
        ]
      }

    };
  },
  created() {
    // 页面创建时默认加载数据
    this.onSubmit();
    this.findType();
  },
  methods: {
    async findProducts() {
      const { data: res } = await productApi.findAllProducts();
      if (res.code === 200) {
        this.ProductList = res.data.list;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 点击查询按钮触发查询，包括分页和条件
    async onSubmit() {
      const { data: res } = await productApi.searchProduct(this.page, this.pageSize, this.findResult);
      console.log(res)
      if (res.code === 200) {
        this.ProductList = res.data.pageResult.rows; // 获取学生数据
        this.total = res.data.pageResult.total; // 获取总条数
      }
    },
    // 分页查询
    async findByPage(page, pageSize, findResult = {}) {
      const { data: res } = await productApi.findByPage(page, pageSize, findResult);
      if (res.code === 200) {
        this.ProductList = res.data.pageResult.rows; // 获取学生数据
        this.total = res.data.pageResult.total; // 获取总条数
      }
    },
    // 查找班级
    async findType() {
      const { data: res } = await typeApi.findAllType();
      if (res.code === 200) {
        this.typeList = res.data.list; // 获取班级数据，确保有默认值
      }
    },
    addProduct(){
      this.product = {};
      this.dialogFormVisible = true ;
    },
    // 改变每页显示的条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.findByPage(this.page, this.pageSize, this.findResult); // 重新加载数据
    },
    submitForm() {
      this.$refs.ruleForm.validate(async valid => {
        let url = "/product/addProduct"
        let method = "post"
        if(this.product.pid){
          url = "/product/updateProduct"
          method = "put"
        }
        if (valid) {
          console.log("1111")
          const {data:res} = await productApi.saveProduct(url,method,this.product)
          console.log("res:",res)
          console.log("2222")
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message,
              onClose: () => {
                this.dialogFormVisible = false
                this.onSubmit()
              }
            })
          }else{
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
    // 改变当前页
    handleCurrentChange(val) {
      this.page = val; // 改变当前页
      this.findByPage(this.page, this.pageSize, this.findResult); // 重新加载数据
    },

    // 编辑操作
    handleEdit(index, row) {
      console.log(index, row);
      this.title = '修改商品'
      this.product = row
      this.dialogFormVisible = true
    },

    // 删除操作
    handleDelete(index, row) {
      this.pids = row ? [row.pid] : this.multipleSelection.map(m => m.pid);
      this.$confirm(`是否真的要删除商品号为${this.pids.join(', ')}的商品吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        productApi.deleteProduct(this.pids)
            .then(({ data: res }) => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: this.onSubmit // 删除后重新加载数据
                });
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                });
              }
            })
            .catch((error) => {
              console.error("删除商品失败:", error);
              this.$message({
                type: 'error',
                message: '删除商品失败，请稍后再试！'
              });
            });
      }).catch(() => {
        // 用户取消删除
        console.log("删除操作已取消");
      });
    }

  }
};

</script>

<style>

</style>
